package nc.bs.common.util;

import nc.bs.common.util.pojo.TableMsg;
import nc.jdbc.framework.processor.BeanProcessor;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.vo.pubapp.pattern.exception.ExceptionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author duanyp1
 * @date 2024/3/19 16:25
 */
public class GlFreeAssistUtil {

    private static final Map<String, TableMsg> temp = new HashMap<>();

    public static String buildQuerySQL(String freeDocCode, String targetColumn, String assid) {
        TableMsg msg = temp.computeIfAbsent(freeDocCode, (n) -> queryFreeDocTableMsg(freeDocCode));
        if (Objects.isNull(msg)) {
            ExceptionUtils.wrappBusinessException("#### Not found doc : " + freeDocCode);
        }
        return "select " + targetColumn + " from " + msg.tableName + " where " + msg.pk + " =  (select " + msg.num + " from gl_docfree1 where assid = '" + assid + "') ";
    }

    public static TableMsg queryFreeDocTableMsg(String freeDocCode) {
        String sql = "select md_class.defaulttablename tableName,md_property.name pk ,'f'||fi_freemap.num num from md_class" +
                " left join md_property on md_property.id = md_class.keyattribute " +
                " left join bd_accassitem on bd_accassitem.classid = md_class.id " +
                " left join fi_freemap on fi_freemap.doccode = bd_accassitem.code " +
                " where fi_freemap.num is not null and bd_accassitem.code = '" + freeDocCode + "'";
        return (TableMsg) DaoUtil.executeQuery(sql, new BeanProcessor(TableMsg.class));
    }

    public static String[] queryFreeDocIds(String freeDocCode,String[] codes) {
        TableMsg tableMsg = temp.computeIfAbsent(freeDocCode, (n) -> queryFreeDocTableMsg(freeDocCode));
        GlDocFreeItem item = GlDocFreeItem.getItemByCode(freeDocCode);
        String sql ="select " + tableMsg.pk + " from " + tableMsg.tableName + " where "
                + SQLUtil.buildInCondition(Objects.requireNonNull(item).columnCode,codes) ;
        List<String> pks = DaoUtil.executeQueryList(sql, String.class);
        return pks == null ? new String[0] : pks.toArray(new String[0]);
    }

}
